<script setup>
import topNav from "../../components/topNav.vue";
import { introApi } from "@/services/index";
import { onLoad, onShow, onReachBottom } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import { appInfo, loginSwitch } from "@/services/user";
// import topNav from "../../components/topNav.vue";
import { operation } from "@/utils/num.js";
// import { appShopSelector, appScTransferCreate } from "@/services/transfer";
import { appCategory } from "@/services/goods";
import {
  appStockQuery,
  appStockInQuery,
  appStockQueryOne,
} from "@/services/transfer.js";

// const goodsList = ref([]);
// const payNum = ref(0);
// const payPrice = ref(0);
// const oldPayPrice = ref(0);
// const goodsListNo = ref([]);
// const selectShopObj = ref({});
//获取商品
const topHeight = ref(uni.getStorageSync("topHight") || 0);
const form = ref({
  categoryId: "",
  pageIndex: 1,
  pageSize: 20,
  barCode: "",
  code: "",
  name: "",
  skuCode: "",
  categoryId: "",
  available: "",
  showAll: true,
  sortField: "",
  sortOrder: "",
});

const showSelect = ref("");

onLoad((e) => {
  getAppCategory();
  if (uni.getStorageSync("selectShopType")) {
    showSelect.value = uni.getStorageSync("selectShopType");
    // getChartBusiness();
    // getChartCategory();
    // getChartProduct();
  }

  getAppProductQuery();
});

onReachBottom(() => {
  console.log("触底了");
  getAppProductQuery();
});
const sortFun = (str) => {
  if (form.value.sortField == str) {
    form.value.sortField = str;
    // sortOrder.value=sortOrder.value=='desc'?'asc':sortOrder.value=='desc'?'':'desc'
    if (form.value.sortOrder == "desc") {
      form.value.sortOrder = "asc";
    } else if (form.value.sortOrder == "asc") {
      form.value.sortOrder = "";
      form.value.sortField = "";
    } else if (form.value.sortOrder == "") {
      form.value.sortOrder = "desc";
    }
  } else {
    form.value.sortField = str;
    form.value.sortOrder = "desc";
  }

  getAppProductQuery(1);
  // if (selectLive.value >= 3) {
  //   getChartProduct(1);
  // } else {
  //   getChartCategory(1);
  // }
};

//商品分类
const categoryList = ref([]);
const newCategoryList = ref([]);
const getAppCategory = async () => {
  try {
    let res = await appCategory();
    categoryList.value = res.data;
    // form.value.categoryId = res.data[0].id;
    // getappStockQuery(1);

    let arr = [];
    let newArr = [];
    let newArr2 = [];

    res.data.forEach((item, index) => {
      if (!item.parentId) {
        arr.push({ ...item, select: false, children: [] });
      } else {
        newArr.push({ ...item });
      }
    });
    arr.forEach((item, index) => {
      newArr.forEach((item2, index2) => {
        if (item.id == item2.parentId) {
          // item2.children = item.children || [];

          item.children.push({ ...item2, select: false, children: [] });
          newArr.splice(index2, 1);
        }
      });
    });
    arr.forEach((item, index) => {
      item.children.forEach((element, index) => {
        newArr.forEach((item2, index2) => {
          if (element.id == item2.parentId) {
            element.children.push({ ...item2, select: false });
          }
        });
      });
    });
    newCategoryList.value = arr;
  } catch (e) {}
};

console.log(form.value);

const productData = ref([]);
const shopStock = ref([]);

const loading = ref("");
const getAppProductQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
    loading.value = "";
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = null;

    if (showSelect.value == "admin") {
      res = await appStockInQuery(form.value);
    } else {
      res = await appStockQuery(form.value);
    }
    if (res.code == 200) {
      productData.value = productData.value.concat(res.data.datas);

      form.value.pageIndex = form.value.pageIndex + 1;

      if (res.data.datas.length < form.value.pageSize) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
    } else {
    }

    console.log(res);
  } catch (e) {}
};

const searchFun = () => {
  getAppProductQuery(1);
};
const goodsShow = ref(false);
const upper = (e) => {
  console.log(e);
};
const lower = (e) => {
  console.log(e);
};
const scroll = (e) => {
  console.log(e);
};
const selectItem = async (item) => {
  console.log(item);
  let res = await appStockQueryOne({ productId: item.id, showAll: true });
  if (res.code == 200) {
    goodsShow.value = true;
    shopStock.value = res.data.datas;
  }
};
//无网状态
const connected = () => {
  getAppCategory();

  getAppProductQuery();
};

const goDetail = (item) => {
  uni.navigateTo({
    url:
      "/pages/transfer/sock_on/index?item=" +
      encodeURIComponent(
        JSON.stringify({
          id: item.id,
          name: item.name,
          image: item.image,
          code: item.dhCode ? item.dhCode : item.barCode ? item.barCode : "--",
          stockNum: item.stockNum,
          unit: item.unit,
          scId: item.scId,
        })
      ),
  });
};
</script>

<template>
  <view class="bg">
    <topNav
      :title="'库存查询'"
      @save="saveFun"
      :border="true"
      rType="save"
    ></topNav>
    <!-- <up-navbar
      title="手机收银"
      bgColor="#ffffff"
      @rightClick="rightClick"
      :autoBack="true"
      :safeAreaInsetTop="true"
      :fixed="true"
      :placeholder="true"
      :leftText="'返回'"
      :border="true"
    >
      <template #right><text @click="clearFun">清空</text> </template>
    </up-navbar> -->
    <view class="top" :style="'top: calc( 88rpx + ' + topHeight + 'px);'">
      <view class="search-k">
        <up-search
          shape="square"
          placeholder="商品条码/名称/拼音码"
          v-model="form.keyword"
          :showAction="false"
          @search="searchFun"
        ></up-search>
      </view>
    </view>
    <view class="content">
      <view class="content-k">
        <view
          class="content-item content-item-top"
          :style="'top: calc( 180rpx + ' + topHeight + 'px);'"
          v-if="productData.length > 0"
        >
          <view class="content-item-name">商品名称</view>
          <view class="content-item-kc" @click="sortFun('stockNum')"
            ><text>库存</text>
            <view class="shure-icon">
              <up-icon
                class="play-left-fill"
                name="play-left-fill"
                :color="
                  form.sortField == 'stockNum' && form.sortOrder == 'asc'
                    ? '#2979ff'
                    : '#C9CDD4'
                "
                size="18rpx"
              ></up-icon>
              <up-icon
                class="play-right-fill"
                name="play-right-fill"
                :color="
                  form.sortField == 'stockNum' && form.sortOrder == 'desc'
                    ? '#2979ff'
                    : '#C9CDD4'
                "
                size="18rpx"
              ></up-icon>
            </view>
          </view>
          <!-- <view class="content-item-sj" @click="sortFun('price')"
            ><text>售价</text
            ><view class="shure-icon">
              <up-icon
                class="play-left-fill"
                name="play-left-fill"
                :color="
                  form.sortField == 'price' && form.sortOrder == 'asc'
                    ? '#2979ff'
                    : '#C9CDD4'
                "
                size="18rpx"
              ></up-icon>
              <up-icon
                class="play-right-fill"
                name="play-right-fill"
                :color="
                  form.sortField == 'price' && form.sortOrder == 'desc'
                    ? '#2979ff'
                    : '#C9CDD4'
                "
                size="18rpx"
              ></up-icon>
            </view>
          </view> -->
        </view>
        <view
          class="content-item"
          v-for="(item, index) in productData"
          :key="index"
          @click="selectItem(item)"
        >
          <view class="content-item-name">
            <view class="content-item-name-left">
              <image :src="item.image" mode="scaleToFill" />
            </view>
            <view class="content-item-name-right">
              <view class="content-item-name-right-title"
                ><text>{{ item.name }}</text></view
              >
              <view class="content-item-name-right-bm"
                ><text>{{ item.categoryName }}</text></view
              >
            </view>
          </view>
          <view
            class="content-item-kc"
            :class="{ 'content-item-kc-to ': item.stockNum < 5 }"
            ><text>{{ item.stockNum }}</text>
            <up-icon
              v-if="item.stockNum < 5 || item.stockNum > 100"
              name="warning-fill"
              :color="
                item.stockNum < 5
                  ? '#FF5722'
                  : item.stockNum >= 5 && item.stockNum > 100
                  ? '#00B42A'
                  : '#1679fb'
              "
              size="34rpx"
            ></up-icon>
          </view>
          <!-- <view class="content-item-sj content-item-kc-price"
            ><text>¥{{ item.price }}</text>
          </view> -->
        </view>
      </view>

      <view
        class="noData"
        v-if="productData.length <= 0 && loading == 'noMore'"
      >
        <view class="noData-img">
          <image src="@/static/nodate/datas.png" mode="scaleToFill" />
          <view>暂无商品 </view>
        </view>
      </view>

      <view
        class="loading-form"
        v-if="
          loading &&
          productData.length > 0 &&
          productData.length >= form.pageSize
        "
        ><van-loading size="24rpx" v-if="loading == 'Loading'"
          ><text class="loading-text">加载中...</text>
        </van-loading>
        <text class="loading-text" v-if="loading == 'More'">加载更多</text>
        <text class="loading-text" v-if="loading == 'noMore'"
          >~没有数据了~</text
        >
      </view>

      <!-- <view
        class="content-item"
        v-for="(item, index) in goodsList"
        :key="index"
      >
        <view class="content-item-left"
          ><image :src="item.image" mode="scaleToFill"
        /></view>
        <view class="content-item-right">
          <view class="content-item-right-title">
            <text>{{ item.name }}</text>
          </view>
          <view class="content-item-right-index">
            <view>
              <view class="content-item-right-num">
                <view class="content-item-right-num-left"
                  ><text>{{ item.categoryName }}</text>
                </view>
              </view>
              @click="priceClick(item, index, 1)"
              <view class="content-item-right-price"
                ><text>¥</text> {{ item.taxPrice }}</view
              ></view
            >
            <view class="content-item-right-num-right">
              <up-number-box
                v-model="item.transferNum"
                @change="valChange"
                min="0"
              ></up-number-box>
            </view>
          </view>
        </view>
      </view> -->
    </view>
  </view>

  <up-popup
    :show="goodsShow"
    @close="goodsShow = false"
    mode="center"
    round="15"
  >
    <view class="popup-center">
      <view class="popup-top">
        <view class="popup-top-left">
          <image :src="shopStock[0].image" mode="scaleToFill" />
        </view>
        <view class="popup-top-right">
          <view class="popup-top-right-name">{{ shopStock[0].name }}</view>
          <view class="popup-top-right-des">{{
            shopStock[0].categoryName
          }}</view>
        </view>
      </view>

      <view class="content-goods">
        <scroll-view
          :scroll-top="0"
          scroll-y="true"
          class="scroll-Y"
          @scrolltoupper="upper"
          @scrolltolower="lower"
          @scroll="scroll"
        >
          <view class="class-goods-item class-goods-item-top">
            <view class="class-goods-title"> 门店 </view>
            <view class="class-goods-shop"> 库存 </view>
            <view class="class-goods-uit"> 单位 </view>
          </view>
          <view
            class="class-goods-item"
            v-for="(item, index) in shopStock"
            :key="index"
            @click="goDetail(item)"
          >
            <view class="class-goods-title">{{ item.shopName }} </view>
            <view class="class-goods-shop"> {{ item.stockNum }} </view>
            <view class="class-goods-uit"> {{ item.unit }} </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </up-popup>

  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
